<template>
  <div class="main">
    <div>
      <NCard title="用户登录">
        <div>
          <NForm>
            <NFormItem>
              <NInput v-model:value="user.username" placeholder="请输入用户名"></NInput>
            </NFormItem>
            <NFormItem>
              <NInput
                type="password"
                v-model:value="user.password"
                placeholder="请输入密码"
              ></NInput>
            </NFormItem>
          </NForm>
        </div>
        <template #action>
          <NSpace>
            <NButton type="primary" @click="login" :loading="loading">登录</NButton>
            <NButton type="error">重置</NButton>
          </NSpace>
        </template>
      </NCard>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/userStore'
const { updateUserInfo } = useUserStore()

import { useRouter } from 'vue-router'
const router = useRouter()

import { useMessage, NCard, NForm, NFormItem, NInput, NButton, NSpace } from 'naive-ui'
const message = useMessage()

import type { BaseResult } from '@/types/BaseResult'
import { Api } from '@/types/Api'

const user = ref({
  username: '',
  password: '',
})
const loading = ref(false)

const login = () => {
  Api.post('/auth', user.value, (data: BaseResult) => {
    if (!data.success) {
      message.error(data.message)
      return
    }
    updateUserInfo(() => {
      loading.value = false
      message.success('登录成功')
      router.push('/user/main')
    })
  })
}
</script>

<style scoped>
.main {
  height: 100dvh;
  width: 100dvw;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
